<template>
    <div class="container">
        <!-- 地址输入框 -->
        <div class="search-box">
            <input
                v-model="inputAddress"
                placeholder="输入地址（如：深圳市龙岗区龙翔大道2001号）"
            />
            <button @click="handleSearch">定位</button>
        </div>

        <!-- 地图容器 -->
        <div id="map-container" style="width: 100%; height: 70vh"></div>
    </div>
</template>

<script setup>
import { onMounted, ref } from "vue";

// 高德地图API key（需先注册申请）
const MAP_KEY = "7f7416d9d1985f9dd2441be454ee47f1";

// 需要标注的地点列表
const locations = [{ name: "深圳市大数据研究院", address: "深圳市龙岗区龙翔大道2001号" }];

// 初始化地图
const initMap = () => {
    // https://restapi.amap.com/v3/geocode/geo?key=f301f7d304f13f5b484af863325e907f&address=%E6%B7%B1%E5%9C%B3%E5%B8%82%E7%A6%8F%E7%94%B0%E5%8C%BA%E7%A6%8F%E4%BF%9D%E8%A1%97%E9%81%93%E7%A6%8F%E4%BF%9D%E7%A4%BE%E5%8C%BA%E6%B7%B1%E6%B8%AF%E5%9B%BD%E9%99%85%E7%A7%91%E6%8A%80%E5%9B%ADE%E6%A0%8B13%E5%B1%82
    const map = new AMap.Map("map-container", {
        zoom: 13, // 初始缩放级别
        center: [114.05378, 22.503554], // 初始中心点（深圳市福田区福保街道福保社区深港国际科技园E栋13层）
    });

    // 添加地理编码插件
    AMap.plugin("AMap.Geocoder", () => {
        const geocoder = new AMap.Geocoder();
        getGeocode("深圳市龙岗区龙翔大道2001号");
    });
};
const lnglat = ref("");
const getGeocode = async (address) => {
    debugger;
    try {
        new AMap.Geocoder().getLocation(address, (status, result) => {
            debugger;
            if (status === "complete" && result.geocodes.length) {
                const { lng, lat } = result.geocodes[0].location;
                lnglat.value = `${lng},${lat}`;
            } else {
                console.error("地址解析失败");
            }
        });
    } catch (error) {
        console.error("地图加载失败", error);
    }
};

onMounted(() => {
    initMap();
    // 调用示例
    // getGeocode("深圳市龙岗区龙翔大道2001号");
});

// onMounted(() => {
//     // 异步加载高德地图API
//     const script = document.createElement("script");
//     script.src = `https://webapi.amap.com/maps?v=2.0&key=${MAP_KEY}`;
//     script.onload = initMap;
//     document.head.appendChild(script);
// });
</script>
<style scoped>
.container {
    padding: 20px;
}
.search-box {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
}
input {
    flex: 1;
    padding: 8px;
}
button {
    padding: 8px 20px;
    background: #409eff;
    color: white;
    border: none;
}
.info-window {
    padding: 10px;
    min-width: 200px;
}
</style>
